<template>
  <div class="app-container">
    <el-form :inline="true" :model="search" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="search.title" placeholder="请输入商品查询关键字" />
      </el-form-item>
      <el-form-item label="卖点">
        <el-input v-model="search.sellPoint" placeholder="请输入卖点查询关键字" />
      </el-form-item>
      <el-form-item label="价格区间">
        <el-col :span="11">
          <el-input v-model="search.minPrice" placeholder="请输入价格最低值" />
        </el-col>
        <el-col class="line" :span="2" style="text-align:center">-</el-col>
        <el-col :span="11">
          <el-input v-model="search.maxPrice" placeholder="请输入价格最高值" />
        </el-col>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchAction">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="add">
          <i class="el-icon-upload el-icon-plus" />
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <el-table :data="items" border style="width: 100%;">
      <el-table-column prop="id" label="商品编号" width="80" />
      <el-table-column prop="title" label="商品名称" />
      <el-table-column prop="sellPoint" label="卖点" />
      <el-table-column label="价格" width="100">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ (scope.row.price/100).toFixed(2) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="库存" width="80" />
      <el-table-column prop="itemCat.name" label="分类" width="80" />
      <el-table-column label="状态" width="150">
        <template slot-scope="scope">
          <!-- <div class="tag-group">
            <el-tag v-if="scope.row.status==1" effect="dark">正常</el-tag>
            <el-tag v-if="scope.row.status==2" type="danger" effect="dark">下架</el-tag>
          </div>-->
          <el-switch
            v-model="scope.row.status"
            active-text="上架"
            inactive-text="下架"
            :active-value="1"
            :inactive-value="2"
            @change="topOrDown(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="created" label="创建时间" width="120" />
      <el-table-column prop="updated" label="更新时间" width="120" />

      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleClick(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="deleteClick(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog title="编辑商品" :visible.sync="dialogVisible" width="80%" top="0px">
      <el-form ref="form" :model="item" label-width="80px">
        <el-form-item label="商品名称">
          <el-input v-model="item.title" />
        </el-form-item>
        <el-form-item label="商品卖点">
          <el-input v-model="item.sellPoint" type="textarea" />
        </el-form-item>
        <el-form-item label="商品价格">
          <el-input v-model="item.price" />
        </el-form-item>
        <el-form-item label="商品库存">
          <el-input v-model="item.num" />
        </el-form-item>
        <el-form-item label="条形码">
          <el-input v-model="item.barcode" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="upload-demo"
            action="/api/file/upload/item"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-button size="small" type="primary" @click="categoryDialogVisible = true">选择类目</el-button>
          <span v-text="item.cname" />
        </el-form-item>

        <el-form-item label="商品详情">
          <tinymce v-model="item.content" :height="300" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="onSubmit">保存</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 图片预览dialog -->
    <el-dialog :visible.sync="previewDialogVisible">
      <img width="100%" :src="dialogImagdialogIeUrl" alt>
    </el-dialog>
    <!-- 选择分类dialog -->
    <el-dialog :visible.sync="categoryDialogVisible" title="类目选择">
      <el-tree ref="tree" :props="props" :load="loadNode" lazy />
      <el-button type="primary" @click="chooseCategory">保存</el-button>
      <el-button @click="categoryDialogVisible = false">取消</el-button>
    </el-dialog>
  </div>
</template>

<script>
import { fetchItems, updateItem, fetchItemCats, addItemAndDesc } from '@/api/item'
import Tinymce from '@/components/Tinymce'
export default {
  name: 'Products',
  components: { Tinymce },
  data() {
    return {
      props: {
        label: 'label',
        isLeaf: 'isLeaf'
      },
      // 总条数
      total: 0,
      limit: 10,
      // 当前页
      currentPage: 1,
      search: {
        title: '',
        sellPoint: '',
        minPrice: '',
        maxPrice: ''
      },
      items: [], // 商品列表数据
      item: {
        image: []
      }, // 当前新增、编辑的商品对象
      // fileList: [], //上传商品图片列表
      dialogVisible: false, // 客户编辑弹框的标识
      categoryDialogVisible: false, // 选择分类弹出框
      previewDialogVisible: false, // 图片预览弹窗标识
      dialogImageUrl: '' // 当前预览url
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    topOrDown(row) {
      // console.log(row.id, row.status);
      // row.status = 1;
      this.$confirm('是否确认操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 执行删除操作
          const params = { id: row.id, status: row.status }
          updateItem(params).then(res => {
            this.$message({
              type: 'success',
              message: '操作成功! '
            })
          })
        })
        .catch(() => {
          row.status = row.status == 1 ? 2 : 1
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
    },
    deleteClick(row) {
      this.$confirm('是否确认删除该客户数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 执行删除操作
          deleteCustomer(row.id).then(res => {
            this.fetchData()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 当调整每页条数时触发
    handleSizeChange(val) {
      this.limit = val
      // console.log(`每页 ${val} 条`);
      this.fetchData()
    },
    // 当切换页码时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
      // console.log(`当前页: ${val}`);
    },
    searchAction() {
      this.currentPage = 1
      this.fetchData()
    },
    fetchData() {
      // 向后台发起请求，获取数据
      // http://localhost:8081/api/customer/list
      const query = {
        page: this.currentPage,
        limit: this.limit,
        minPrice: this.search.minPrice * 100,
        maxPrice: this.search.maxPrice * 100,
        title: this.search.title,
        sellPoint: this.search.sellPoint
      }
      fetchItems(query).then(res => {
        // console.log('success...'+JSON.stringify(res));
        // 当前页数据
        this.items = res.data.data
        // 总条数
        this.total = res.data.total
      })
    },
    handleClick(row) {
      this.dialogVisible = true
      // console.log(row);
      this.customer = {
        id: row.id,
        username: row.username,
        age: row.age,
        sex: row.sex,
        type: row.type,
        address: row.address,
        avatar: row.avatar
      }
    },
    onSubmit() {
      this.item.image = this.item.image.join(',')
      this.item.price = this.item.price * 100// 元-> 分
      console.log(JSON.stringify(this.item))

      addItemAndDesc(this.item).then(res => {
        this.$message({
          type: 'success',
          message: '商品新增成功'
        })
        // 关闭弹出层
        this.dialogVisible = false
        // 刷新
        this.fetchData()
      })
      // this.customer
      /*
      if (this.item.id == "") {
        // 新增
        console.log(this.item);
      } else {
        // 更新
        updateCustomer(this.customer).then(res => {
          // 关闭弹出层
          this.dialogVisible = false;
          // 刷新
          this.fetchData();
        });
      }*/
    },
    add() {
      this.customer = {
        id: '',
        username: '',
        age: '',
        sex: '',
        address: '',
        avatar: ''
      }
      this.dialogVisible = true
    },
    // 上传成功回调
    handleSuccess(res, file) {
      // 上传成功后，将图片地址存放到图片数组中
      this.item.image.push(res.data)
      console.log('current fileList == >' + this.fileList)
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
      // 从this.fileList中移除当前删除的file（file.response.data）即可
      const i = this.item.image.indexOf(file.response.data)
      if (i != -1) {
        this.item.image.splice(i, 1)
      }
      console.log('current fileList == >' + this.item.image)
    },
    handlePreview(file) {
      console.log(file)
      // 显示预览窗口
      this.previewDialogVisible = true
      // 显示预览图片
      this.dialogImageUrl = file.response.data
    },
    // 动态加载tree节点数据 node：当前操作的节点  resolve 用于返回数据
    loadNode(node, resolve) {
      console.log(node)
      const id = node.data == undefined ? 0 : node.data.id
      fetchItemCats(id).then(res => {
        return resolve(res.data)
      })
    },
    chooseCategory() {
      // 类目选择确定
      // 确认是否已经选择类目
      // this.$refs.tree.getCurrentNode() 获取当前选中节点{"id":837,"label":"太阳镜","isLeaf":true}
      if (this.$refs.tree.getCurrentNode() == null) {
        this.$message({
          type: 'warning',
          message: '请选择商品分类'
        })
        return
      }
      if (this.$refs.tree.getCurrentNode().isLeaf == false) {
        this.$message({
          type: 'warning',
          message: '请选择具体商品分类子分类'
        })
        return
      }
      this.item.cid = this.$refs.tree.getCurrentNode().id
      this.item.cname = this.$refs.tree.getCurrentNode().label
      this.categoryDialogVisible = false
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
